package com.huaqin.develop.demotest.controller;

import com.alibaba.fastjson.JSONObject;
import com.huaqin.develop.demotest.mapper.UniquePurchaseMapper;
import com.huaqin.develop.demotest.mapper.WmsPurchaseMapper;
import com.huaqin.develop.demotest.pojo.WmsPurchase;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
//mq的监听器，指定topic是TopicTest，消费者组consumerGroupTest
@RocketMQMessageListener(topic = "fourbrothertopic", consumerGroup = "consumerGroupTest")
@Slf4j
public class ConsumeController implements RocketMQListener<String> {

    @Autowired
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private UniquePurchaseMapper uniquePurchaseMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Override
    public void onMessage(String message) {
        log.info("------- ConsumeController 处理消息: {}", message);
        //将message消息映射成WmsPurchase实体
        WmsPurchase wmsPurchase = JSONObject.parseObject(message, WmsPurchase.class);

        // 注入redisson
        // 获取锁对象
        RLock lock = redisson.getLock("lockName");
        try {
            // 1. 最常见的使用方法
            //lock.lock();
            // 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁
            //lock.lock(10, TimeUnit.SECONDS);
            // 3. 尝试加锁，最多等待2秒，上锁以后8秒自动解锁
            boolean res = lock.tryLock();
            if (res) { //成功
                //然后再使用PurchaseId查询数据库，有数据，则直接放过不做处理
                if (null == wmsPurchaseMapper.selectByPurchaseId(wmsPurchase.getPurchaseId())) {
                    //数据库没有数据，就进行插入操作，
                    if (wmsPurchaseMapper.insert(wmsPurchase) > 0) {
                        //插入成功就把purchaseid塞进redis里，过期时间是72小时
                        redisTemplate.opsForValue().set(wmsPurchase.getPurchaseId().toString(), wmsPurchase.toString(), 1, TimeUnit.HOURS);
                    }
                } else {
                    redisTemplate.opsForValue().set(wmsPurchase.getPurchaseId().toString(), wmsPurchase.toString(), 1, TimeUnit.HOURS);
                    log.info("数据库已保留该数据");
                    //自动触发告警机制
                }
            }
            //todo 抛出异常，会触发 消费者 重试机制
            // int i = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            //释放锁
            RLock lockName = redisson.getLock("lockName");
            if (lockName.isLocked()) {
                if (lockName.isHeldByCurrentThread()) {
                    lockName.unlock();
                }
            }
        }


        //取重表
     /*   log.info("映射后实体消息"+ JSON.toJSONString(wmsPurchase));
        if (uniquePurchaseMapper.selectByPurchaseId(wmsPurchase.getPurchaseId().intValue())  == null){
            if (null == wmsPurchaseMapper.selectByPurchaseId(wmsPurchase.getPurchaseId())){
                //数据库没有数据，就进行插入操作，

                if (wmsPurchaseMapper.insert(wmsPurchase)>0){
                    //插入成功就把purchaseid塞进unique_purchase
                    UniquePurchase  uniquePurchase =   new UniquePurchase();
                    uniquePurchase.setPurchaseId(wmsPurchase.getPurchaseId().intValue());
                    log.info("插入取重表消息："+ JSON.toJSONString(uniquePurchase));
                    uniquePurchaseMapper.insert(uniquePurchase);
                }
            }else {
                log.info("数据库已保留该数据");
                //自动触发告警机制
            }
        }else {
            log.info("取重表已有这条采购单数据");
        }*/




        /*
         *  redis + uniquekey
         * */
        //首先判断redis里面是否有这条采购单数据，通过PurchaseId查询，有数据，则直接放过不做处理
      /* if (redisTemplate.opsForValue().get(wmsPurchase.getPurchaseId().toString())==null){
           //然后再使用PurchaseId查询数据库，有数据，则直接放过不做处理
           if (null == wmsPurchaseMapper.selectByPurchaseId(wmsPurchase.getPurchaseId())){
               //数据库没有数据，就进行插入操作，
               if (wmsPurchaseMapper.insert(wmsPurchase)>0){
                   //插入成功就把purchaseid塞进redis里，过期时间是72小时
                   redisTemplate.opsForValue().set(wmsPurchase.getPurchaseId().toString(),wmsPurchase.toString(),1, TimeUnit.HOURS);
               }
           }else {
               redisTemplate.opsForValue().set(wmsPurchase.getPurchaseId().toString(),wmsPurchase.toString(),1, TimeUnit.HOURS);
               log.info("数据库已保留该数据");
               //自动触发告警机制
           }
       }else {
           log.info("缓存已保留该数据");
           //自动触发告警机制
       }*/


    }
}
